package com.yk.pool;

import java.util.concurrent.*;

/**
 * Created by dingkl on 2017/7/27.
 */
public class ServerPool {
    private static ThreadPoolExecutor executorPool = null;
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = CPU_COUNT + 1; //线程池维护线程的最少数量
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;//线程池维护线程的最大数量
    private static final int KEEP_ALIVE = 5;//线程池维护线程所允许的空闲时间 这个地方的单位是
    private static final int WORK_QUEUE_SIZE = 20;// 线程池所使用的缓冲队列

    /**
     * 获取线程池执行器
     *
     * @return
     */
    public synchronized static ThreadPoolExecutor getExecutorPool() {
        if (executorPool == null) {
            RejectedExecutionHandlerImpl rejectionHandler = new RejectedExecutionHandlerImpl();
            ThreadFactory threadFactory = Executors.defaultThreadFactory();
            executorPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(WORK_QUEUE_SIZE), threadFactory, rejectionHandler);
        }
        return executorPool;
    }

    public static void submit(CommonInterface commonInterface){
        if (executorPool!=null){
            executorPool.execute(new WorkThread(commonInterface));
        }
    }

    public static void close(){
        if (executorPool!=null)
            executorPool.shutdown();
    }

}
